import { useState, useEffect } from "react";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
export interface IRichEditorProps {
  onChange?: (arg: string) => void;
}

export default function RichEditor(props: IRichEditorProps) {
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState("<p>hello</p>");
  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: "请输入内容...",
  };

  const handleChange = (editor: IDomEditor) => {
    console.log(editor.getHtml());
    setHtml(editor.getHtml());
    if (props.onChange) {
      props.onChange(editor.getHtml()); //将富文本内容返回给表单
    }
  };
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  return (
    <div>
      <Toolbar editor={editor} mode="default" defaultConfig={toolbarConfig} />
      <Editor
        onChange={handleChange}
        defaultConfig={editorConfig}
        value={html}
        style={{ height: "300px", border: "1px solid #d8d8d8" }}
      />
    </div>
  );
}
